﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace THO7AlgoritmTimerApplication {
    class find_pixel : VisionAlgorithm {
        public find_pixel(String name) : base(name) { }
        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            /*BitmapData bmpdata = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadOnly, sourceImage.PixelFormat);
            IntPtr ptr = bmpdata.Scan0;
            int regellengte = Math.Abs(bmpdata.Stride);
            int bytes = regellengte * sourceImage.Height;
            byte[] rgbValues = new byte[bytes+1];
            System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
            int x1 = regellengte;
            int y1 = sourceImage.Height;
            int x2 = 0;
            int y2 = 0;
            for (int regelnummer = 0; regelnummer < sourceImage.Height; regelnummer++) {
                for (int convolutie = 0; convolutie < regellengte; convolutie += 3) {
                    int pixel = regelnummer * regellengte + convolutie;
                    if (rgbValues[pixel] == 0 && rgbValues[pixel+1] == 0 && rgbValues[pixel+2] == 0) {
                        if (regelnummer < y1) {
                            y1 = regelnummer;
                        }else if (regelnummer > y2) {
                            y2 = regelnummer;
                        }if (convolutie < x1) {
                            x1 = convolutie;
                        }else if (convolutie > x2){
                            x2 = convolutie;
                        }
                    }
                }
            }
            sourceImage.UnlockBits(bmpdata);*/
            int x1 = sourceImage.Width;
            int y1 = sourceImage.Height;
            int x2 = 0;
            int y2 = 0;
            for (int x = 0; x < sourceImage.Width; x++) {
                for (int y = 0; y < sourceImage.Height; y++) {
                    Color c = sourceImage.GetPixel(x, y);
                    if (c.R < 10 && c.G < 10 && c.B < 10) {
                        if (y < y1) {
                            y1 = y;
                        }if (y > y2) {
                            y2 = y;
                        }if (x < x1) {
                            x1 = x;
                        }if (x > x2) {
                            x2 = x;
                        }
                    }
                }
            }
            Bitmap dest = sourceImage.Clone(new Rectangle(x1, y1, (x2 - x1), y2 - y1), sourceImage.PixelFormat);
            return dest;
        }
    }
}
